package com.hmall.item.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDto;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private IItemService itemService;

    @GetMapping("/list")
    public PageDTO<Item> list(@RequestParam Integer page,
                              @RequestParam Integer size) {
//        分页条件
        Page<Item> ipage = new Page<>(page, size);
//        查询条件
        //LambdaQueryWrapper<Item> queryWrapper = new LambdaQueryWrapper();
//        排序条件
        //queryWrapper.orderByDesc(Item::getId);

        Page<Item> itemPage = itemService.page(ipage);

        return new PageDTO<>(itemPage.getTotal(), itemPage.getRecords());
    }

    @GetMapping("/{id}")
    public Item ids(@PathVariable Long id) {
        return itemService.getById(id);

    }

    @PostMapping
    public void add(@RequestBody Item item) {
        if (StringUtils.isEmpty(item.getName())) {
            throw new RuntimeException("名字不能为空");
        }
        item.setStatus(1);
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        itemService.save(item);
    }

    @PutMapping("/status/{id}/{status}")
    public void update(@PathVariable Long id,@PathVariable Integer status) {
        Item item = new Item();
        item.setId(id);
        item.setStatus(status);
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        itemService.updateById(item);
    }
    @DeleteMapping("/{id}")
    public void delete(@PathVariable long id){
        itemService.removeById(id);
    }
}
